<?php
declare (strict_types = 1);

namespace app\admin\model\erp;

use bbweb\traits\ModelTrait;
use bbweb\basic\BaseModel;

/**
 * 会计目录模型
 */
class ErpSubjects extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'erp_subjects';

    use ModelTrait;

    // 设置字段信息
    protected $schema = [
        'id'	        => 'int',
        'pid'           => 'int',
        'code'          => 'varchar',
        'name'          => 'varchar',
        'pname'         => 'varchar',
        'sys'           => 'tinyint',
        'level'         => 'tinyint',
        'rel_id'        => 'int',
        'rel_type'      => 'char',//user,type,good,bank,acca资产,accb折旧
        'remark'        => 'varchar',
        'luck'          => 'tinyint',
        'edit_luck'     => 'tinyint',
        'update_at'     => 'int'
    ];

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function typeAll()
    {
        $typeAll = self::order('level ASC')->select()->toArray();
        return $typeAll;
    }

    /**
     * select选择项
     * @param $list
     * @param int $pid
     * @param array $navList
     * @return array
     */
    public static function tidySelect()
    {
        $typeAll = self::order('level ASC')->select()->toArray();
        return self::tidyTree($typeAll);
    }
    /**
     * select选择项-凭证使用
     * @param $list
     * @param int $pid
     * @param array $navList
     * @return array
     */
    public static function tidyCodeSelect()
    {
        $typeAll = self::order('level ASC')->select()->toArray();
        return self::tidyCodeTree($typeAll);
    }

    /**
     * @param $list
     * @param int $pid
     * @param array $navList
     * @return array
     */
    public static function tidyTree($list, $pid = 0, $navList = [])
    {
        foreach ($list as $k => $menu) {
            if ($menu['pid'] == $pid) {
                unset($list[$k]);
                $menu['name'] = $menu['code']. '-' .$menu['name'];
                $children = self::tidyTree($list, $menu['id']);
                $menu['id'] = $menu['code'];
                if($children) {
                    $menu['nocheck'] = true;
                    $menu['children'] = $children;
                }
                $navList[] = $menu;
            }
        }
        return $navList;
    }
    /**
     * 组合树形Table数组
     * @param $list
     * @param int $pid
     * @param array $navList
     * @return array
     */
    public static function treeTable($list, $pid = 0, $navList = [])
    {
        foreach ($list as $k => $menu) {
            if ($menu['pid'] === $pid) {
                unset($list[$k]);
                $children = self::treeTable($list, $menu['id']);
                if($children) {
                    $menu['is_end'] = false;
                    $menu['children'] = $children;
                } else {
                    $menu['is_end'] = true;
                }
                $navList[] = $menu;
            }
        }
        return $navList;
    }
    public static function tidyCodeTree($list, $pid = 0, $navList = [], $name = '')
    {
        foreach ($list as $k => $menu) {
            if ($menu['pid'] == $pid) {
                unset($list[$k]);
                $or_name = empty($name) ? $menu['name']. ' -> ' : $name . $menu['name']. ' -> ';
                $menu['name'] = $menu['code'] . '-' . $name . $menu['name'];
                $children = self::tidyCodeTree($list, $menu['id'], [], $or_name);
                $menu['id'] = $menu['code'];
                if($children) {
                    $menu['nocheck'] = true;
                    $menu['children'] = $children;
                }
                $navList[] = $menu;
            }
        }
        return $navList;
    }

    /**
     * @param $list
     * @return bool
     */
    public static function addCode($list)
    {
        if(!isset($list['rel_id']) || !isset($list['like']) || empty($list['like']) || !isset($list['sys'])) return [];
        self::beginTrans();
        $bool = true;
        $data = [];
        foreach($list['like'] as $k=>$v) {
            $sub = self::where('rel_id',$list['rel_id'])->where('code','like',"{$k}%")->find();
            if($sub) {
                continue;
            }
            $res = self::createCode($list['rel_id'], $k, $list['sys']);
            if(!$res) {
                $bool = false;
                break;
            }
            if(is_array($res)) $data[] = $res;
        }
        self::checkTrans($bool);
        return $bool ? $data : [];
    }

    public static function createCode($rel_id, $code, $sys=0)
    {
        $fsub = self::where('code', '=', $code)->find();
        $name = Vendors::where('id',$rel_id)->value('name');
        if(!$fsub || !$name) return false;
        $level = $fsub['level'] + 1;
        $fcode = self::where('code','like', "{$fsub['code']}%")->where('level',$level)->max('code');
        if($fcode <= $fsub['code']) $fcode = $fsub['code'] . '000';
        $fcode = $fcode + 1;
        $item = [
            'pid'       => $fsub['id'],
            'rel_id'    => $rel_id,
            'rel_type'  => 'user',
            'code'      => $fcode,
            'name'      => $name,
            'pname'     => $fsub['pname'],
            'sys'       => $sys,
            'level'     => $level,
            'luck'      => 1,
            'edit_luck' => 1,
            'update_at' => time()
        ];
        if($res = self::create($item)) {
            return $res->toArray();
        }
        return false;
    }
}
